package com.hk.commons.ssl;

import lombok.Setter;
import lombok.SneakyThrows;

import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Objects;

/**
 * @author Kevin
 */
@Setter
public class CompositeTrustManager implements X509TrustManager {

    private List<X509TrustManager> managers;

    @Override
    @SneakyThrows
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
        if (Objects.nonNull(this.managers)) {
            for (X509TrustManager manager : this.managers) {
                manager.checkClientTrusted(x509Certificates, s);
            }
        }
    }

    @Override
    @SneakyThrows
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
        if (Objects.nonNull(this.managers)) {
            for (X509TrustManager manager : this.managers) {
                manager.checkServerTrusted(x509Certificates, s);
            }
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        if (Objects.nonNull(this.managers)) {
            for (X509TrustManager manager : this.managers) {
                X509Certificate[] acceptedIssuers = manager.getAcceptedIssuers();
                if (Objects.nonNull(acceptedIssuers)) {
                    return acceptedIssuers;
                }
            }
        }
        return new X509Certificate[0];
    }
}
